var config = parent.parent.CONFIG,system=parent.parent.SYSTEM;
if(!config){
	config = parent.parent.parent.CONFIG;
	system = parent.parent.parent.SYSTEM;
}
var _limitMenu = system.MENULIMIT.BASE26;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'base/product/barcodepage';
var handle = {
	doQueryBrand : function(){
			commonDia = $.dialog({
				title : '选择品牌',
				content : 'url:'+config.BASEPATH+'base/brand/to_list_dialog',
				data : {multiselect:false},
				width : 320,
				height : 370,
				max : false,
				min : false,
				cache : false,
				lock: true,
				ok:function(){
					var selected = commonDia.content.doSelect();
					if (!selected) {
						return false;
					}
				},
				close:function(){
					var selected = commonDia.content.doSelect();
					if(selected){
						$("#pd_bd_code").val(selected.bd_code);
						$("#pd_bd_name").val(selected.bd_name);
					}
				},
				cancel:true
			});
	},
	doQueryType : function(){
		commonDia = $.dialog({
			title : '选择商品类别',
			content : 'url:'+config.BASEPATH+'base/type/to_tree_dialog',
			data : {multiselect:true},
			width : 280,
		   	height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					var pd_tp_code = [];
					var pd_tp_name = [];
					var pd_tp_upcode = [];
					for(var i=0;i<selected.length;i++){
						pd_tp_code.push(selected[i].tp_code);
						pd_tp_name.push(selected[i].tp_name);
						pd_tp_upcode.push(selected[i].tp_upcode);
					}
					$("#pd_tp_code").val(pd_tp_code.join(","));
					$("#pd_tp_name").val(pd_tp_name.join(","));
					$("#pd_tp_upcode").val(pd_tp_upcode.join(","));
				}
			},
			cancel:true
		});
	},
	copyBarcode:function(id){
		var grid=$('#grid'),row=grid.getRowData(id);
		grid.setCell(id,'bc_barcode',row.bc_sys_barcode);
	},
	bulkCopyBarcode:function(){
		$.dialog.confirm('确定要批量复制吗？',function(){
			var Ids=$("#grid").jqGrid("getGridParam", "selarrrow");
			var	length= Ids.length;
			for(var i=0;i<length;i++){
				var fuzhi=$("#grid").jqGrid("getRowData", Ids[i]).bc_sys_barcode;
				$('#grid').jqGrid('setCell',Ids[i],'bc_barcode',fuzhi);
			}
		});
	},
	imports:function(){
		$.dialog({
			title : '条形码批量导入',
			content : 'url:'+config.BASEPATH+"base/product/to_import_barcode",
			data: {callback: this.callback},
			width : 550,
			height : 350,
			max : false,
			min : false,
			cache : false,
			lock: true
		});
	},
	save:function(rowId){
		if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
			return;
		};
		var row=$('#grid').jqGrid('getRowData',rowId);
		$.ajax({
			type:"POST",
			url:config.BASEPATH +"base/product/saveOneBarcode",
			data:"bc_barcode="+row.bc_barcode+"&bc_id="+rowId,
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : data.message});
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		}); 
	},
	bulkSaveBarcode:function(){
		var Ids = new Array();
		Ids = $("#grid").jqGrid("getGridParam", "selarrrow");
		$.dialog.confirm('确定要批量保存吗？',function(){
			var len=Ids.length;
			var bc_barcodes = "";
			if(len==0){
				Public.tips({type: 2, content : '没有需要保存的数据！'});
				return;
			}
			var id="";
			var code;
			var bc_ids="";
			var bc_barcodes="";
			var tempCodes="";
			for(var j=0;j<len;j++){
			    id=Ids[j];
				code =$("#grid").jqGrid('getCell', id,'bc_barcode');
				bc_barcodes += code+",";
				bc_ids += id+",";
			} 
			bc_ids=bc_ids.substring(0,bc_ids.length-1);
			bc_barcodes=bc_barcodes.substring(0,bc_barcodes.length-1);
			if(bc_barcodes!= null && bc_barcodes !='' && bc_barcodes.length >0){
				var codeArr = bc_barcodes.split(",");
				var count=0;
				
				bc_barcodes = bc_barcodes.split(",");
				for(var i=0,size=codeArr.length;i<size;i++){
					tempCodes += '@'+bc_barcodes[i]+'@';
					count = tempCodes.split(codeArr[i]).length-1;
					if(count > 1){
						Public.tips({type: 2, content : '有重复条码！'});
						return;
					}
				}
			}
			$.ajax({
				type:"POST",
				url:config.BASEPATH +"base/product/saveAllBarcode",
				data:"bc_ids="+bc_ids+"&bc_barcodes="+bc_barcodes,
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : data.message});
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			}); 
		});
	},
	bulkDelBarcode:function(){
		var Ids = new Array();
		Ids = $("#grid").jqGrid("getGridParam", "selarrrow");
		$.dialog.confirm('数据删除后无法恢复，确定要批量删除吗？',function(){
			var len=Ids.length;
			if(len==0){
				Public.tips({type: 2, content : '没有需要删除的数据！'});
				return;
			}
			var bc_ids="";
			for(var j=0;j<len;j++){
				bc_ids += Ids[j]+",";
			} 
			bc_ids=bc_ids.substring(0,bc_ids.length-1);
			$.ajax({
				type:"POST",
				url:config.BASEPATH +"base/product/delBulkBarcode",
				data:"bc_ids="+bc_ids,
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : data.message});
						/*for(key in Ids){
							$('#grid').jqGrid('delRowData', Ids[key]);
						}*/
						THISPAGE.reloadData();
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			}); 
		});
	},
	delAllBarcode:function(){
		$.dialog.confirm('数据删除后无法恢复，确定要清空吗？',function(){
			$.ajax({
				type:"POST",
				url:config.BASEPATH +"base/product/delAllBarcode",
				data:"",
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : data.message});
						THISPAGE.reloadData();
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			}); 
		});
	},
	printSet:function(){
    	$.dialog({
    		//id设置用来区别唯一性 防止div重复
    	   	id:'printPlan',
    	   	//设置标题
    	   	title:'条码打印设置',
    	   	//设置最大化最小化按钮(false：隐藏 true:关闭)
    	   	max: false,
    	   	min: false,
    	   	lock:true,
    	   	//设置长宽
    	   	width:440,
    	   	height:380,
    	   	//设置是否拖拽(false:禁止，true可以移动)
    	   	drag: true,
    	   	resize:false,
   		   	//设置页面加载处理
  		   	fixed:false,
    	   	content:"url:"+config.BASEPATH+"base/product/to_barcode_plan",
    	   	close: function(){
    	   		
  		   	}
        });
	},
	print:function(printState){//打印状态0直接打印 1打印预览
		var arrayObj = new Array();
		arrayObj=$('#grid').jqGrid('getGridParam','selarrrow');
		var i=0,addMark=0;
		if(arrayObj == "" ){
			Public.tips({type: 2, content : '没有可打印的记录！'});
            return;
        }
        var bc_barcodes = new Array();
        var bc_colornames = new Array();
        var bc_pd_nos= new Array();
        var bc_pd_names = new Array();
        var bc_branames = new Array();
       	var bc_sizenames = new Array();
       	var pd_bd_names = new Array();
       	var pd_sell_prices = new Array();
       	var pd_vip_prices = new Array();
       	var pd_sign_prices = new Array();
       	var pd_grades = new Array();
       	var pd_safes = new Array();
       	var pd_fills = new Array();
       	var pd_executes=new Array();
       	var pd_tp_names =new Array(); 
       	var pd_fabrics =new Array(); 
       	var pd_in_fabrics =new Array(); 
       	var pd_places =new Array(); 
       	var pd_wash_explains =new Array(); 
       	
        if(arrayObj =="")
		{
			return;
		}
		else
		{
			var re= new RegExp("^[0-9]*[1-9][0-9]*$");//验证
			var tag = false;
			var k = 0;
			for (i=0; i<arrayObj.length; i++){
				if($("#grid").jqGrid('getCell', arrayObj[i],'bc_barcode')==""){
					Public.tips({type: 2, content : '请输入条形码！'});
					return;
				}
				var num = $("#grid").jqGrid('getCell', arrayObj[i],'sc_printnumber');
				if(num == ""){
					num = 1+"";
				}
				if(num.match(re)==null){
					Public.tips({type: 2, content : '打印数量只能输入正整数！'});
					return;
				}
				for(var n=0;n<num;n++){
					bc_barcodes[k] =$("#grid").jqGrid('getCell', arrayObj[i],'bc_barcode');
					bc_colornames[k] = $("#grid").jqGrid('getCell', arrayObj[i],'bc_colorname');
					bc_pd_nos[k] = $("#grid").jqGrid('getCell', arrayObj[i],'bc_pd_no');
					bc_branames[k] =  $("#grid").jqGrid('getCell', arrayObj[i],'bc_braname');
					bc_sizenames[k] = $("#grid").jqGrid('getCell', arrayObj[i],'bc_sizename');
					pd_bd_names[k] = $("#grid").jqGrid('getCell', arrayObj[i],'pd_bd_name');
					pd_sell_prices[k] = $("#grid").jqGrid('getCell', arrayObj[i],'pd_sell_price');
					pd_vip_prices[k]= $("#grid").jqGrid('getCell', arrayObj[i],'pd_vip_price');
					pd_sign_prices[k]= $("#grid").jqGrid('getCell', arrayObj[i],'pd_sign_price');
					bc_pd_names[k] = $("#grid").jqGrid('getCell', arrayObj[i],'bc_pd_name');
					pd_fills[k] = $("#grid").jqGrid('getCell', arrayObj[i],'pd_fill');
					pd_safes[k] = $("#grid").jqGrid('getCell', arrayObj[i],'pd_safe');
					pd_grades[k] = $("#grid").jqGrid('getCell', arrayObj[i],'pd_grade');
					pd_executes[k]=$("#grid").jqGrid('getCell', arrayObj[i],'pd_execute');
					pd_tp_names[k]=$("#grid").jqGrid('getCell', arrayObj[i],'pd_tp_name');
					pd_fabrics[k]=$("#grid").jqGrid('getCell', arrayObj[i],'pd_fabric');
					pd_in_fabrics[k]=$("#grid").jqGrid('getCell', arrayObj[i],'pd_in_fabric');
					pd_places[k]=$("#grid").jqGrid('getCell', arrayObj[i],'pd_place');
					pd_wash_explains[k]=$("#grid").jqGrid('getCell', arrayObj[i],'pd_wash_explain');
					k++;
					addMark++;
				}
			}
		}
		if(addMark==0)
		{
			Public.tips({type: 2, content : '请选择要打印的条形码！'});
			return;	
		}
		
		xdPrint.barCode(printState,bc_barcodes,bc_colornames,bc_pd_nos,bc_branames,bc_sizenames,pd_bd_names,pd_sell_prices,pd_sign_prices,pd_vip_prices,pd_grades,pd_safes,pd_fills,bc_pd_names,pd_executes,pd_tp_names,pd_fabrics,pd_in_fabrics,pd_places,pd_wash_explains);
	},
	del: function(rowId){//删除
		if(rowId != null && rowId != ''){
		 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
				$.ajax({
					type:"POST",
					url:config.BASEPATH +"base/product/deleteBarcode",
					data:{"bc_id":rowId},
					cache:false,
					dataType:"json",
					success:function(data){
						if(undefined != data && data.stat == 200){
							Public.tips({type: 3, content : '删除成功!'});
							$('#grid').jqGrid('delRowData', rowId);
						}else{
							Public.tips({type: 1, content : '删除失败!'});
						}
					}
				});
			});
	   }else{
		   Public.tips({type: 1, content : '请选择数据!'});
	   }	
    },
	operFmatter:function(val, opt, row) {
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-copy" title="复制">&#xe63a;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-shenpi" title="保存">&#xe616;</i> <i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '</div>';
		return html_con;
	}
}
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
	},
	initGrid:function(){
		var gridWH = Public.setGrid();
		var colModel = [
		    {name: 'operate', label:'操作',width: 80, fixed:true, formatter: handle.operFmatter, title: false,sortable:false},
		    {name: 'bc_pd_no', label:'货号',index: 'pd_no', width: 100, title: false,fixed:true,sortable:false},
	    	{name: 'bc_pd_name', label:'商品名称',index: 'pd_name', width: 160, title: false,sortable:false},
	    	{name: 'pd_bd_name', label:'品牌',index: 'pd_bd_name', width: 80, title: false,sortable:false},
	    	{name: 'pd_tp_name', label:'类别',index: 'pd_tp_name', width:80, title: false,sortable:false},
	    	{name: 'bc_colorname',label:'颜色',index: 'bc_colorname',width: 60,title: false,fixed:true,sortable:false},
	    	{name: 'bc_sizename',label:'尺码',index: 'bc_sizename',width: 60,title: false,sortable:false},
	    	{name: 'bc_braname',label:'杯型',index: 'bc_braname',width: 40,title: false,sortable:false},
	    	{name: 'pd_sell_price', label:'零售价',index: 'pd_sell_price', width: 80, title: false,sortable:false},
	    	{name: 'bc_sys_barcode',label:'系统条形码',index: 'bc_sys_barcode', width: 150,title: false,sortable:false},
	    	{name: 'bc_barcode',label:'自建条形码',index: 'bc_barcode', width: 150,title: false,editable:true,sortable:false},
	    	{name: 'sc_printnumber',label:'打印数量', index: 'SC_PrintNumber', width: 80, editable:true, title: false,sortable:false},
	    	{name: 'pd_grade',label:'等级', hidden:true},
	    	{name: 'pd_safe',label:'安全标准', hidden:true},
	    	{name: 'pd_fill',label:'填充物',hidden:true},
	    	{name: 'bc_subcode',label:'子码',hidden:true},
	    	{name: 'pd_vip_price', label:'会员价', hidden:true},
	    	{name: 'pd_sign_price',label:'标牌价', hidden:true},
	    	{name: 'pd_execute',label:'执行标准',hidden:true},
	    	{name: 'pd_fabric',label:'面料',hidden:true},
	    	{name: 'pd_in_fabric',label:'里料',hidden:true},
	    	{name: 'pd_place',label:'产地',hidden:true},
	    	{name: 'pd_wash_explain',label:'洗涤说明',hidden:true}
	    ];
		$('#grid').jqGrid({
			url:queryurl,
			datatype: 'json',
			width: gridWH.w-12,
			height: gridWH.h-20,
			gridview: true,
			onselectrow: false,
			cellEdit: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:true,//多选
			viewrecords: true,
			cellsubmit: 'clientArray',//可编辑列在编辑完成后会触发保存事件，clientArray表示只保存到表格不提交到服务器
			rowNum:100,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			scroll: 1,//是否滚动
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
				repeatitems : false,
				id: 'bc_id'  //图标ID
			},
			loadComplete: function(data){
			},
			loadError: function(xhr, status, error){
			}
	    });
	},
	buildParams : function(){
		var params = '';
		params += 'pd_no='+$("#pd_no").val();
		params += '&pd_name='+Public.encodeURI($("#pd_name").val());
		params += '&pd_tp_code='+$("#pd_tp_code").val();
		params += '&pd_bd_code='+$("#pd_bd_code").val();
		params += '&bc_barcode='+Public.encodeURI($("#bc_barcode").val());
		return params;
	},
	reset:function(){
		$("#pd_no").val('');
		$("#pd_name").val('');
		$("#pd_tp_name").val('');
		$("#pd_tp_code").val('');
		$("#pd_tp_upcode").val('');
		$("#pd_bd_name").val('');
		$("#pd_bd_code").val('');
		$("#bc_barcode").val('');
	},
	reloadData:function(data){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		$('#pd_no').on('keyup',function(event){
			if (event.keyCode==13){
				$('#btn-search').click();
			}
		});
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
		//删除
		$('#grid').on('click', '.operating .ui-icon-trash', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			var id = $(this).parent().data('id');
			handle.del(id);
		});
		 //复制
        $('#grid').on('click', '.operating .ui-icon-copy', function (e) {
        	e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
				return ;
			}
            var id = $(this).parent().data('id');
        	handle.copyBarcode(id);
        });
		 //修改
        $('#grid').on('click', '.operating .ui-icon-shenpi', function (e) {
        	e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
				return ;
			}
            var id = $(this).parent().data('id');
        	handle.save(id);
        });
        //批量复制
		$('#btn-bulkCopyBarcode').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
				return ;
			}
			handle.bulkCopyBarcode();
		});
		//批量保存
		$('#btn-bulkSaveBarcode').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.UPDATE)) {
				return ;
			}
			handle.bulkSaveBarcode();
		});
		//批量删除
		$('#btn-bulkDelBarcode').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			handle.bulkDelBarcode();
		});
		//清空，删除当前商家所有条码
		$('#btn-DelAllBarcode').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			handle.delAllBarcode();
		});
		
		//打印设置
		$('#btn-printSite').on('click', function(e){
			e.preventDefault();
			handle.printSet();
		});
		//打印
		$('#btn-print').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.PRINT)) {
				return ;
			}
			handle.print(0);
		});
		//打印预览
		$('#btn-print-preview').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.PRINT)) {
				return ;
			}
			handle.print(1);
		});
		$('#btn-import').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.IMPORT)) {
				return ;
			};
			handle.imports();
		});
	}
}
THISPAGE.init();